package com.logInterceptor.service;

import com.logInterceptor.model.AuditLogRecord;
import com.logInterceptor.model.Customer;
import com.utils.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import java.util.List;

public class BusinessService {

    private HibernateUtil hibernateUtil = new HibernateUtil();
    private SessionFactory sessionFactory = hibernateUtil.getSessionFactory();

    private void saveOrUpdateCustomer(Customer customer) {
        Transaction tx = null;
        Session session = null;

        try {
            AuditLogInterceptor interceptor = new AuditLogInterceptor();
            session = sessionFactory.withOptions().interceptor(interceptor).openSession();
            interceptor.setSession(session);
            tx = session.beginTransaction();
            session.saveOrUpdate(customer);
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null) {
                tx.rollback();
            }
        } finally {
            assert session != null;
            session.close();
        }
    }

    private  void findAllAuditLogRecords() {
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            List results = session.createQuery("from AuditLogRecord").list();
            for (Object result : results) {
                AuditLogRecord record = (AuditLogRecord) result;
                System.out.println("**********");
                System.out.println("message:" + record.message);
                System.out.println("entityId:" + record.entityId);
                System.out.println("entityClass:" + record.entityClass);
                System.out.println("created:" + record.created);
            }
            tx.commit();

        } catch (RuntimeException e) {
            if (tx != null) {
                tx.rollback();
            }
        } finally {
            session.close();
        }
    }

    public void test() {
        Customer customer = new Customer("Tom");
        saveOrUpdateCustomer(customer);

        customer.setName("Mike");
        saveOrUpdateCustomer(customer);

        findAllAuditLogRecords();
        sessionFactory.close();
    }

    public static void main(String args[]) {
        new BusinessService().test();
    }
}
